// src/items/items.controller.ts
import {Body, Controller, Get, ParseFilePipeBuilder, Post, Query, UploadedFile, UseInterceptors} from '@nestjs/common';
import { DemoService } from './demo.service';
import {CreateMessagePipe} from "../../common/pipes/createmessage.pipe";
import {AddDemoDto, DeleteDemoDto, ImportDemoDto, UpdateDemoDto} from "./dto/req-demo.dto";
import {RepeatSubmit} from "../../common/decorators/repeat-submit.decorator";
import {FileInterceptor} from "@nestjs/platform-express";
import {ApiException} from "../../common/exceptions/api.exception";
import {ExcelService} from "../common/excel/excel.service";

  @Controller('project')
export class DemoController {
  constructor(
    private readonly demoService: DemoService,
    private readonly excelService: ExcelService,
  ) {}

  @Get('list')
  async findAll() {
    return this.demoService.findAll();
  }

  @Post('add')
  @RepeatSubmit()
  async add(@Body(CreateMessagePipe) addDemoDto: AddDemoDto) {
    await this.demoService.add(addDemoDto);
  }

  @Post('detail')
  @RepeatSubmit()
  async findItem(@Body(CreateMessagePipe) addDemoDto: DeleteDemoDto) {
    return this.demoService.findItemById(addDemoDto.projectId);
  }

  @Post('update')
  @RepeatSubmit()
  async update(@Body(CreateMessagePipe) updateDemoDto: UpdateDemoDto) {
    await this.demoService.update(updateDemoDto);
  }

  @Post('delete')
  @RepeatSubmit()
  async delete(@Body(CreateMessagePipe) deleteDemoDto: DeleteDemoDto) {
    await this.demoService.delete(deleteDemoDto.projectId);
  }

  @Post('remove')
  @RepeatSubmit()
  async remove(@Body(CreateMessagePipe) deleteDemoDto: DeleteDemoDto) {
    await this.demoService.softDeleteProject(deleteDemoDto.projectId);
  }

    /* 用户导入 */
    @Post('importData')
    @RepeatSubmit()
    @UseInterceptors(FileInterceptor('file'))
    async importData(
      @UploadedFile(
        new ParseFilePipeBuilder()
          .addMaxSizeValidator({
            maxSize: 1024 * 1024 * 5,
          })
          .addFileTypeValidator({
            fileType:
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })
          .build({
            exceptionFactory: (error) => {
              throw new ApiException(
                '文件格式错误！ 文件最大为5M，且必须是 xlsx 格式',
              );
            },
          }),
      )
        file: Express.Multer.File,
    ) {
      const data = await this.excelService.import<ImportDemoDto>(
        ImportDemoDto,
        file,
      );
      await this.demoService.importData(data);
    }
}
